package com.hb.trade.api.manager.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hb.core.pojo.center.au.entity.User;
import com.hb.core.pojo.center.au.dto.AdminLoginUserDTO;
import com.hb.core.pojo.enums.RoleSignEnum;
import com.hb.trade.client.center.RoleClient;
import com.hb.trade.client.center.UserClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.fzzn.core.auth.shiro.JwtToken;
import org.fzzn.core.auth.shiro.util.ShiroUtil;
import org.fzzn.core.cache.redis.StringRedisService;
import org.fzzn.core.component.jwt.util.JwtUtils;
import org.fzzn.core.model.enums.MsgEnum;
import org.fzzn.core.model.enums.UserTypeEnum;
import org.fzzn.core.model.msg.Message;
import org.fzzn.core.model.msg.ResponseDto;
import org.fzzn.core.model.user.login.LoginModel;
import org.fzzn.core.model.user.login.SimpleUserExample;
import org.fzzn.core.util.Enums;
import org.fzzn.core.util.ResultUtil;
import org.fzzn.core.web.anno.Version;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 系统用户登录相关
 *
 * @author zhaojk
 */
@Slf4j
@Version(1.0)
@Api(tags = {"系统用户登录相关接口"})
@RequestMapping("/{version}")
@RestController
public class AdminLoginController {

    protected final UserClient userClient;
    protected final RoleClient roleClient;
    protected final StringRedisService redisService;

    public AdminLoginController(UserClient userClient,
                                RoleClient roleClient,
                                StringRedisService redisService) {
        this.userClient = userClient;
        this.roleClient = roleClient;
        this.redisService = redisService;

    }

    /**
     * 用户名密码登录
     *
     * @param
     * @return
     */
    @ApiOperation(value = "用户名密码登录", notes = "用户名密码登录", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名(支持手机号作为参数)", dataTypeClass = String.class, required = true),
            @ApiImplicitParam(name = "password", value = "密码", dataTypeClass = String.class, required = true),
            @ApiImplicitParam(name = "roleSign", value = "登录角色", dataTypeClass = int.class, required = true)
    })
    @PostMapping("/admin/login")
    public ResponseDto userLogin(@RequestBody AdminLoginUserDTO adminUser) {
        // 参数验证
        String uname = adminUser.getUsername();
        if (StrUtil.isEmpty(uname)) {
            return ResultUtil.fail(MsgEnum.USERNAME_NOT_ALLOW_EMPTY);
        }
        String pword = adminUser.getPassword();
        if (StrUtil.isEmpty(pword)) {
            return ResultUtil.fail(MsgEnum.PASSWORD_NOT_ALLOW_EMPTY);
        }

        JwtToken token = new JwtToken(adminUser.getUsername(), adminUser.getPassword());

        ResponseDto resp = ShiroUtil.login(token);

        // 无任何返回表示登录成功
        if (resp == null) {
            SimpleUserExample loginUser = token.getLoginUser();

            // 如果是超级管理员直接返回
            Long userId = loginUser.getId();
            Message<User> userMessage = userClient.getByUserId(userId);
            User data = userMessage.getData();
            if (!Enums.equals(UserTypeEnum.SUPER_ADMIN, data.getUserType())) {
                 return ResultUtil.fail("非平台的超级管理员,不能登录系统");
            }

            JSONObject extInfo = loginUser.getExtInfo();
            loginUser.setExtInfo(extInfo);

            // 重新更新一下redis中的信息
            LoginModel<SimpleUserExample> model = LoginModel.get(loginUser, token.getToken());
            JwtUtils.stayToken(model);

            return loginResponse(loginUser, token.getToken());

            // 判断该用户是否拥有指定的业务角色
//            Message<Boolean> hasRoleMsg = roleClient.hasRoleSign(userId, RoleSignEnum.BUSINESS.getCode());

//            // 成功登录 start
//            if (hasRoleMsg.getData()) {
//                JSONObject extInfo = loginUser.getExtInfo();
//                extInfo.putOpt("roleSign", RoleSignEnum.BUSINESS.getCode());
//                loginUser.setExtInfo(extInfo);
//
//                // 重新更新一下redis中的信息
//                LoginModel<SimpleUserExample> model = LoginModel.get(loginUser, token.getToken());
//                JwtUtils.stayToken(model);
//
//                return loginResponse(loginUser, token.getToken());
//            }
//            // 成功登录 end
//
//            return ResultUtil.fail("你还没有[" + RoleSignEnum.BUSINESS.getShowName() + "]的角色, 不能以该身份登录系统");\

        }
        return resp;
    }

    /**
     * 登录信息响应对象
     *
     * @param userEntity
     * @param webToken
     * @return
     */
    private ResponseDto loginResponse(SimpleUserExample userEntity, String webToken) {
        // 返回前端不显示密码字段
        userEntity.setPassword(null);
        JSONObject respJSON = JSONUtil.parseObj(userEntity);

        respJSON.set("token", webToken);

        Long id = userEntity.getId();
        Message<User> userInfo = userClient.getByUserId(id);
        if (userInfo.isSuccess()) {
            respJSON.set("userType", userInfo.getData().getUserType());
        }


        // 查询用户的业务角色列表, 20220208, 需求变更为登录系统后不再选择角色, 所以这里不再查询用户的所有角色了
        // Message<List<RoleDTO>> biddingRolesMsg = roleClient.listBiddingRoles(userEntity.getId());
        // respJSON.set("biddingRoles", biddingRolesMsg.getData());

        return ResultUtil.msg(true, respJSON);
    }




}
